package com.fortune.schedule;

import com.fortune.dal.dao.CreditCardInfoDAO;
import com.fortune.dal.model.Card;
import com.fortune.dal.model.CreditCardInfo;
import com.fortune.service.CardService;
import com.fortune.service.ScheduleService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class BillEmailLoadSchedule {

    protected static final Logger logger = LoggerFactory.getLogger(BillEmailLoadSchedule.class);

    @Autowired
    private CreditCardInfoDAO creditCardInfoDAO;

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private CardService cardService;

    private List<String> mails = Lists.newArrayList();

    @Value("${spring.profiles.active}")
    private String env;

    @Scheduled(fixedRate = 1000 * 60 * 60 * 24)
    public void run() {
        try {
            if (!"prd".equals(env)) {
                return;
            }
            mails.clear();
            List<CreditCardInfo> creditCardInfos = creditCardInfoDAO.queryByModel(new CreditCardInfo());
            for (CreditCardInfo creditCardInfo : creditCardInfos) {
                Card card = cardService.queryCard(creditCardInfo.getCardId());
                if (StringUtils.isBlank(creditCardInfo.getBillEmail()) || mails.contains(creditCardInfo.getBillEmail())) {
                    continue;
                }
                scheduleService.loadEmail(card.getCustId(), creditCardInfo.getBillEmail(), creditCardInfo.getBillEmailPassword());
                mails.add(creditCardInfo.getBillEmail());
            }
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }


//    /**
//     * 　　*　解析邮件，把得到的邮件内容保存到一个StringBuffer对象中，解析邮件
//     * 　　*　主要是根据MimeType类型的不同执行不同的操作，一步一步的解析
//     */
//
//    public static String getMailContent(Part part) throws Exception {
//
//        String contentType = part.getContentType();
//        // 获得邮件的MimeType类型
////        System.out.println("邮件的MimeType类型: " + contentType);
//
//        int nameIndex = contentType.indexOf("name");
//
//        boolean conName = false;
//
//        if (nameIndex != -1) {
//            conName = true;
//        }
//
////        System.out.println("邮件内容的类型:　" + contentType);
//
//        if (part.isMimeType("text/plain") && conName == false) {
//            // text/plain 类型
//            return (String) part.getContent();
//        } else if (part.isMimeType("text/html") && conName == false) {
//            // text/html 类型
//            String str = (String) part.getContent();
//
//            return new String(str.getBytes(), "utf-8");
//        } else if (part.isMimeType("multipart/*")) {
//            // multipart/*
//            Multipart multipart = (Multipart) part.getContent();
//            int counts = multipart.getCount();
//            StringBuffer sb = new StringBuffer();
//            for (int i = 0; i < counts; i++) {
//                sb.append(getMailContent(multipart.getBodyPart(i)));
//            }
//            return sb.toString();
//        } else if (part.isMimeType("message/rfc822")) {
//            // message/rfc822
//            return getMailContent((Part) part.getContent());
//        }
//        return null;
//    }

//    private void test(Message me) throws BusinessException {
//        try {
//            String subject = me.getSubject();
//            if ("平安信用卡电子账单".equals(subject)) {
//                Date date1 = me.getSentDate();
//                        Date date2 = me.getReceivedDate() ;
//
//
//                System.out.println(me.getContent());
//                System.out.println(me.getContentType());
//                        System.out.println(me.isMimeType("text/plain"));
//                        System.out.println(me.isMimeType("text/html"));
//                System.out.println(me.isMimeType("multipart/*"));
//                        System.out.println(MimeUtility.decodeText(me.getSubject()););
//                String content = getMailContent(me);
//                Html html = new Html(content, "");
//                System.out.println(html.getDocument());
//                System.out.println(me.getSubject());
//                System.out.println(DateFormatUtils.yyyyMMdd.format(date1));
//
//                ///
//                System.out.println("账单日:" + html.xpath("/html/body/table/tbody/tr[7]/td/table/tbody/tr/td[1]/table/tbody/tr[2]/td/table/tbody/tr[1]/td[2]/text()").toString());
//                System.out.println("本期还款日:" + html.xpath("/html/body/table/tbody/tr[7]/td/table/tbody/tr/td[1]/table/tbody/tr[2]/td/table/tbody/tr[2]/td[2]/span/strong/text()").toString());
//                System.out.println("本期应还金额:" + html.xpath("/html/body/table/tbody/tr[7]/td/table/tbody/tr/td[3]/table/tbody/tr[2]/td/table/tbody/tr/td[2]/table/tbody/tr[1]/td/strong/text()").toString());
//                System.out.println("本期最低应还金额:" + html.xpath("/html/body/table/tbody/tr[7]/td/table/tbody/tr/td[3]/table/tbody/tr[2]/td/table/tbody/tr/td[2]/table/tbody/tr[3]/td/text()").toString());
//                System.out.println("信用额度:" + html.xpath("/html/body/table/tbody/tr[7]/td/table/tbody/tr/td[1]/table/tbody/tr[2]/td/table/tbody/tr[3]/td[2]/text()").toString());
//                System.out.println("取现额度:" + html.xpath("/html/body/table/tbody/tr[7]/td/table/tbody/tr/td[1]/table/tbody/tr[2]/td/table/tbody/tr[4]/td[2]/text()").toString());
//                System.out.println("积分:" + html.xpath("/html/body/table/tbody/tr[11]/td/table/tbody/tr[3]/td[1]/strong/text()").toString());
//            }
//        } catch (Exception ex) {
//            BusinessException.throwBusinessException(ex);
//        }
//    }

}
